package web_config

import (
	"github.com/pkg/errors"
	"github.com/xinliangnote/go-gin-api/internal/pkg/core"
	"github.com/xinliangnote/go-gin-api/internal/repository/mongodb/web_config"
	"go.mongodb.org/mongo-driver/mongo"
)

type WebConfigData struct {
	Content string
}

func (s *service) Create(ctx core.Context, data *WebConfigData) (err error) {

	model := web_config.NewModel()
	last, err := model.GetLast(s.db.GetDb())
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return err
	}
	model.Content = data.Content
	if last.Content != "" {
		model.Id = last.Id
		err = model.Update(s.db.GetDb())
		return err
	} else {
		err = model.Create(s.db.GetDb())
		return err
	}

}

func (s *service) GetLatest(ctx core.Context) (webConfig web_config.WebConfig, err error) {
	model := web_config.NewModel()
	webConfig, err = model.GetLast(s.db.GetDb())
	return webConfig, err
}
